package com.yuxl.ai.knowledge.service;

import com.yuxl.ai.knowledge.entity.AiKnowledge;
import com.yuxl.ai.knowledge.repository.AiKnowledgeRepository;
import com.yuxl.common.auth.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * @Author : yuxl
 * @create 2025/7/10 下午6:09
 */
@Slf4j
@Service
public class AiKnowledgeService {
    
    @Resource
    private AiKnowledgeRepository aiKnowledgeRepository;
    @Resource
    private JwtUtil jwtUtil;

    public Flux<AiKnowledge> findAll() {
        return aiKnowledgeRepository.findAll();
    }

    public Mono<AiKnowledge> findById(Long id) {
        return aiKnowledgeRepository.findById(id)
                .defaultIfEmpty(new AiKnowledge());
    }

    public Mono<Void> deleteById(Long id) {
        return aiKnowledgeRepository.deleteById(id);
    }

    public Mono<AiKnowledge> create(AiKnowledge entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setCreateBy(user.id());
                    entity.setUpdateBy(user.id());
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiKnowledgeRepository.save(entity);
                });
    }

    public Mono<Integer> count(AiKnowledge entity) {
        return aiKnowledgeRepository.count(entity);
    }


    public Flux<AiKnowledge> page(AiKnowledge entity, int page, int size) {
        long offset = (long) (page - 1) * size;
        return aiKnowledgeRepository.page(entity, size, offset);
    }


    public Flux<AiKnowledge> list(AiKnowledge entity) {
        return aiKnowledgeRepository.list(entity);
    }

    public Mono<AiKnowledge> updateById(AiKnowledge entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setUpdateBy(user.id());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiKnowledgeRepository.updateById(entity)
                            .flatMap(rows -> rows > 0 ? aiKnowledgeRepository.findById(entity.getId()) : Mono.empty());
                });
    }

}
